package com.xw.floatlib.view;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.xw.floatlib.FloatActionController;
import com.xw.floatlib.MusicData;
import com.xw.floatlib.R;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;


/**
 * Des:悬浮窗的布局
 */
public class FloatLayout extends FrameLayout implements View.OnClickListener {

    private WindowManager mWindowManager;
    private ImageView mFloatView;
    private ImageView image_last;
    private ImageView image_start;
    private ImageView image_next;
    private ImageView image_cancle;
    private float mTouchStartX;
    private float mTouchStartY;
    private WindowManager.LayoutParams mWmParams;
    private Context mContext;
    private View view;
    private LinearLayout linear_menu;
    private boolean isShowImageBtn = false;
    private int screenWidth;
    private int x;
    private int y;
    //是否正在播放
    private boolean isPlaying = true;
    private Handler handler = new Handler();
    private FloatRoundSeekBar float_seekbar;
    //悬浮窗是否被销毁
    private boolean isWindowLive;
    //音乐集合
    private List<MusicData> musicList = new ArrayList<>();
    //当前播放下标
    private int musicIndex;
    private RequestOptions options;
    private String mPlateId;

    public FloatLayout(Context context) {
        this(context, null);
        mContext = context;
    }

    public FloatLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        LayoutInflater.from(context).inflate(R.layout.float_normal_view, this);
        //浮动窗口按钮
        mFloatView = (ImageView) findViewById(R.id.iv_show_control_view);
        image_last = (ImageView) findViewById(R.id.image_last);
        image_start = (ImageView) findViewById(R.id.image_start);
        image_next = (ImageView) findViewById(R.id.image_next);
        image_cancle = (ImageView) findViewById(R.id.image_cancle);
        view = findViewById(R.id.ll_float_normal);
        linear_menu = findViewById(R.id.linear_menu);
        float_seekbar = findViewById(R.id.float_seekbar);

        view.setVisibility(GONE);
        DisplayMetrics dm = new DisplayMetrics();
        mWindowManager.getDefaultDisplay().getMetrics(dm);
        screenWidth = dm.widthPixels;

        mFloatView.setOnClickListener(this);
        image_last.setOnClickListener(this);
        image_start.setOnClickListener(this);
        image_next.setOnClickListener(this);
        image_cancle.setOnClickListener(this);

        options = new RequestOptions().placeholder(R.drawable.float_music_icon)
                .error(R.drawable.float_music_icon).circleCrop();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {

        // 获取相对屏幕的坐标，即以屏幕左上角为原点
        x = (int) event.getRawX();
        y = (int) event.getRawY();
        //下面的这些事件，跟图标的移动无关，为了区分开拖动和点击事件
        int action = event.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mTouchStartX = event.getX();
                mTouchStartY = event.getY();

                break;
            case MotionEvent.ACTION_MOVE:
                //图标移动的逻辑在这里
                float mMoveStartX = event.getX();
                float mMoveStartY = event.getY();
                // 如果移动量大于3才移动
                if (Math.abs(mTouchStartX - mMoveStartX) > 3
                        && Math.abs(mTouchStartY - mMoveStartY) > 3) {
                    // 更新浮动窗口位置参数
                    mWmParams.x = (int) (x - mTouchStartX);
                    mWmParams.y = (int) (y - mTouchStartY);
                    mWindowManager.updateViewLayout(this, mWmParams);
                    return super.onInterceptTouchEvent(event);
                }
                break;
            case MotionEvent.ACTION_UP:
                float endX = event.getRawX();

                //根据最终手指停留位置，悬浮窗吸边效果实现
                if(endX>screenWidth/2){
                    mWmParams.x = (int) (screenWidth-getWidth());
                    mWindowManager.updateViewLayout(this, mWmParams);
                }else {
                    mWmParams.x = (int) 0;
                    mWindowManager.updateViewLayout(this, mWmParams);
                }

                float upX = event.getX();
                float upY = event.getY();
                //view移动轨迹大于30  ，不处理子View点击事件
                if(Math.abs(upX-mTouchStartX)>30 && Math.abs(upY - mTouchStartY)>30){
                    return true;
                }

                break;
                default:
                    break;
        }

        return super.onInterceptTouchEvent(event);
    }


    /**
     * 将小悬浮窗的参数传入，用于更新小悬浮窗的位置。
     *
     * @param params 小悬浮窗的参数
     */
    public void setParams(WindowManager.LayoutParams params) {
        mWmParams = params;
    }

    /**
     * 更新图片，进度条
     */
    public void upDataUI(List<MusicData> dataBean) {
        if (dataBean.size() == musicList.size()){
            for (int i = 0; i < dataBean.size(); i++) {

                if (!dataBean.get(i).getMusicId().equals(musicList.get(i).getMusicId())){
                    musicList.clear();
                    musicList.addAll(dataBean);
                    break;
                }
            }
        }else {
            musicList.clear();
            musicList.addAll(dataBean);
        }
        Glide.with(mContext).load(dataBean.get(musicIndex).getIamgePath()).apply(options).into(mFloatView);
    }

    /**
     * 设置最大进度条
     */
    public void setMaxProgress(int maxLength){
        float_seekbar.setMax(maxLength);
    }

    /**
     * 更新进度跳
     */
    public void updataProgress(int progress,int postion){
        float_seekbar.setProgress(progress);
        musicIndex = postion;
    }

    @Override
    public void onClick(View v) {

        if (isShowImageBtn) handler.removeCallbacks(runnable);
        int i = v.getId();
        if (i == R.id.iv_show_control_view) {
            if (!isShowImageBtn) {
                linear_menu.setVisibility(VISIBLE);
                isShowImageBtn = true;
            } else {
                linear_menu.setVisibility(GONE);
                isShowImageBtn = false;
                adscrop();
//                try {
//                    Class<?> activiyClass = Class.forName("com.sobey.tvlive2.ui.RadioShowActivity");
////                    Class<?> activiyClass = Class.forName("com.xw.floatlib.MusicActivity");
//                    Intent intent = new Intent();
//                    intent.setClass(mContext,activiyClass);
//                    intent.putExtra("music_list", (Serializable) musicList);
//                    intent.putExtra("music_position",musicIndex);
//                    intent.putExtra("playState",isPlaying);
//                    intent.putExtra("radio_show_id",mPlateId);
////                    intent.putExtra("progress",float_seekbar.getProgress());
//                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                    mContext.startActivity(intent);
//
//                    isShowImageBtn = false;
//                    linear_menu.setVisibility(GONE);
//                    adscrop();
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
            }

        } else if (i == R.id.image_last) {
            FloatActionController.getInstance().lastMusic();
            isPlaying = true;
            image_start.setImageResource(R.drawable.float_image_stop);
        } else if (i == R.id.image_start) {
            if (isPlaying){
                isPlaying = false;
                image_start.setImageResource(R.drawable.float_image_start);
            }else{
                isPlaying = true;
                image_start.setImageResource(R.drawable.float_image_stop);
            }
            FloatActionController.getInstance().stop2Start();
        } else if (i == R.id.image_next) {
            FloatActionController.getInstance().nextMusic();
            isPlaying = true;
            image_start.setImageResource(R.drawable.float_image_stop);
        } else if (i == R.id.image_cancle) {
            FloatActionController.getInstance().cancle();
            handler.removeCallbacks(runnable);
        }

        handler.postDelayed(runnable,3000);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            isShowImageBtn = false;
            linear_menu.setVisibility(GONE);
            adscrop();
        }
    };

    /**
     * 吸边
     */
    private void adscrop(){

        if (isWindowLive) {
            if (x > screenWidth / 2) {
                mWmParams.x = (int) (screenWidth);
                mWindowManager.updateViewLayout(this, mWmParams);
            } else {
                mWmParams.x = (int) 0;
                mWindowManager.updateViewLayout(this, mWmParams);
            }
        }
    }

    /**
     * 隐藏
     */
    public void hide(){
        view.setVisibility(GONE);
    }

    /**
     * 显示
     */
    public void show() {
        view.setVisibility(VISIBLE);
        if (linear_menu.getVisibility() ==VISIBLE){
            linear_menu.setVisibility(GONE);
        }
        adscrop();
    }

    /**
     * 开始/暂停
     */
    public void startOrStop(boolean isStart){
        if (isStart){
            isPlaying = true;
            image_start.setImageResource(R.drawable.float_image_stop);
        }else{
            isPlaying = false;
            image_start.setImageResource(R.drawable.float_image_start);
        }
    }

    public void windowState(boolean isLive){
        isWindowLive = isLive;
        if (isWindowLive){
            handler.removeCallbacks(runnable);
        }
    }

    public boolean getWindowState(){
        return isWindowLive;
    }

    //设置音频频道ID
    public void setRadioID(String plateId) {
        mPlateId = plateId;
    }

    //返回当前播放音乐的id
    public String getRadioProgramID() {
        if (musicList.size() > 1)
            return musicList.get(musicIndex).getMusicId();
        else
            return null;
    }

    /**
     * 移除悬浮窗，清除数据
     */
    public void remove() {
        musicList.clear();
    }
}
